package com.bawei.module_live.gift

import android.app.Activity
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.lifecycle.LifecycleCoroutineScope
import com.bawei.module_live.R
import com.bawei.module_live.adapter.GiftAdapter
import com.bawei.module_live.gift.GiftApi
import com.bawei.module_live.version1.GiftEntity
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.opensource.svgaplayer.SVGACallback
import com.opensource.svgaplayer.SVGAImageView
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGAVideoEntity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import okhttp3.ResponseBody
import retrofit2.Retrofit
import java.io.File
import java.net.URL

object GiftEffectHelper {
    fun showGiftDialog(
        context: Context,
        giftList: List<GiftEntity>,
        svgaImageView: SVGAImageView,
        cacheDir: File,
        coroutineScope: CoroutineScope,
        onDismiss: (() -> Unit)? = null
    ) {
        val dialog = BottomSheetDialog(context)
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_gift_list, null)
        val rv = view.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.rv_gift)
        rv.layoutManager = androidx.recyclerview.widget.GridLayoutManager(context, 4)
        rv.adapter = GiftAdapter(giftList) { gift ->
            coroutineScope.launch {
                try {
                    svgaImageView.stopAnimation(true)
                    svgaImageView.setVideoItem(null)
                    if (gift.svgaPath.startsWith("http")) {
                        val parser = SVGAParser(context)
                        parser.decodeFromURL(URL(gift.svgaPath), object : SVGAParser.ParseCompletion {
                            override fun onComplete(videoItem: SVGAVideoEntity) {
                                svgaImageView.visibility = View.VISIBLE
                                svgaImageView.setVideoItem(videoItem)
                                svgaImageView.loops = 1
                                svgaImageView.startAnimation()
                                svgaImageView.callback = object : SVGACallback {
                                    override fun onFinished() {
                                        svgaImageView.visibility = View.GONE
                                        svgaImageView.setVideoItem(null)
                                    }
                                    override fun onPause() {}
                                    override fun onRepeat() {}
                                    override fun onStep(frame: Int, percentage: Double) {}
                                }
                            }
                            override fun onError() {
                                Toast.makeText(context, "动画解析失败", Toast.LENGTH_SHORT).show()
                                svgaImageView.visibility = View.GONE
                                svgaImageView.setVideoItem(null)
                            }
                        })
                    } else {
                        val filename = gift.svgaPath.removeSuffix(".svga")
                        val api = Retrofit.Builder()
                            .baseUrl("http://10.161.9.80:7015/")
                            .build()
                            .create(GiftApi::class.java)
                        val responseBody: ResponseBody = api.downloadSvga(filename)
                        val file = File(cacheDir, "$filename.svga")
                        file.outputStream().use { output ->
                            responseBody.byteStream().copyTo(output)
                        }
                        playSvga(context, file, svgaImageView)
                    }
                } catch (e: Exception) {
                    Toast.makeText(context, "动画加载失败", Toast.LENGTH_SHORT).show()
                }
            }
            dialog.dismiss()
        }
        dialog.setContentView(view)
        dialog.setOnDismissListener {
            onDismiss?.invoke()
        }
        dialog.show()
        dialog.window?.apply {
            setGravity(Gravity.START or Gravity.CENTER_VERTICAL)
            setLayout(
                android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.MATCH_PARENT
            )
        }
    }

    fun playSvga(context: Context, file: File, svgaImageView: SVGAImageView) {
        svgaImageView.stopAnimation(true)
        svgaImageView.setVideoItem(null)
        svgaImageView.visibility = View.VISIBLE
        val parser = SVGAParser(context)
        parser.decodeFromInputStream(file.inputStream(), file.name, object : SVGAParser.ParseCompletion {
            override fun onComplete(videoItem: SVGAVideoEntity) {
                svgaImageView.setVideoItem(videoItem)
                svgaImageView.loops = 1
                svgaImageView.startAnimation()
                svgaImageView.callback = object : SVGACallback {
                    override fun onFinished() {
                        svgaImageView.visibility = View.GONE
                        svgaImageView.setVideoItem(null)
                    }
                    override fun onPause() {}
                    override fun onRepeat() {}
                    override fun onStep(frame: Int, percentage: Double) {}
                }
            }
            override fun onError() {
                Toast.makeText(context, "动画解析失败", Toast.LENGTH_SHORT).show()
                svgaImageView.visibility = View.GONE
                svgaImageView.setVideoItem(null)
            }
        }, true)
    }
} 